clear; clc; close all;
dataset = 'movielen100k';
load(strcat('../noncvx-lowrank/data/recsys/', dataset, '.mat'));

% data = data(1:500, 1:500);
[row, col, val] = find(data);

val = val - mean(val);
val = val/std(val);

idx = randperm(length(val));


traIdx = idx(1:floor(length(val)*0.5));
tstIdx = idx(ceil(length(val)*0.5): end);

clear idx;

traData = sparse(row(traIdx), col(traIdx), val(traIdx));
traData(size(data,1), size(data,2)) = 0;

lambdaMax = topksvd(traData, 1, 5);
gradLambda = lambdaMax*(0.6).^(1:15);

para.maxIter = 100;
para.decay = 0.8;

para.test.row  = row(tstIdx);
para.test.col  = col(tstIdx);
para.test.data = val(tstIdx);

%% start testing
switch (dataset)
    case 'movielen100k'
        lambda = 9.1;
        para.tol = 1e-2;
        
        para.maxR = 100;
    case 'movielen1m'
        lambda = 17;
        para.tol = 1e-3;
        
        para.exact = 1;
        para.maxR = 200;
    case 'movielen10m'
        lambda = 45;
        
        para.tol = 1e-1;
        para.maxR = 300;
end

gndtruth = val(tstIdx);

% para.exact = 0;
% para.decay = 0.85;
% [U2, S2, V2, out2] = AccSoftImpute(traData, lambda, para);
% predict = partXY((U2*S2)', V2', row(tstIdx), col(tstIdx), length(gndtruth))';
% % predict(predict < 1) = 1;
% % predict(predict > 5) = 5;
% % predict = round(predict);
% L0(1) = sum(predict == gndtruth)/length(predict);
% L1(1) = sum(abs(predict - gndtruth))/length(predict);
% L2(1) = sum((predict - gndtruth).^2)/length(predict);

% [U1, S1, V1, out1] = APGLog(traData, 3.5, para);
% predict = partXY((U1*S1)', V1', row(tstIdx), col(tstIdx), length(gndtruth))';
% predict(predict < 1) = 1;
% predict(predict > 5) = 5;
% predict = round(predict);
% L0(2) = sum(predict == gndtruth)/length(predict);
% L1(2) = sum(abs(predict - gndtruth))/length(predict);
% L2(2) = sum((predict - gndtruth).^2)/length(predict);

[~, ~, valOML] = find(traData);

for i = 1:40
    % [U3, Theta, V3, numiter ] = OR1MP(size(traData, 1), size(traData, 2), i, find(traData ~= 0), valOML);
    t = tic;
    [U3, Theta, V3, numiter ] = EOR1MP(size(traData, 1), size(traData, 2), i, traData);
    Time(i) = toc(t);
    RMSE(i) = MatCompRMSE(U3, V3, diag(Theta), row(tstIdx), col(tstIdx), val(tstIdx))
end

plot(Time, RMSE);
hold on;

para.decay = 0.9;
para.exact = 0;
[U, S, V, out]  = AccSoftImpute(traData', 9, para);
% [U, S, V, out] = SoftImputeALS( traData', 1e-4, 3, para );
out.Time = out.Time*2/3;

plot(out.Time, out.RMSE);



